import 'package:flutter/material.dart';
import 'scrollNotification_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScrollControllerTestRoute(),
      routes: <String, WidgetBuilder> {
        'new_page': (context)=>ScrollNotoficationTestRoute(),
      },
    );
  }
}

class ScrollControllerTestRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new ScrollControllerTestRouteState();
}

class ScrollControllerTestRouteState extends State<ScrollControllerTestRoute> {
  ScrollController _controller = new ScrollController();
  bool showToTopBtn = false; // 是否显示返回顶部按钮

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //监听滚动事件
    _controller.addListener(() {
      print(_controller.offset); // 打印滚动位置
      if (_controller.offset < 200 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_controller.offset >= 200 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    //为了避免内存泄漏，移出监听
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text('滚动控制'),
      ),
      body: new Scrollbar(
        child: new ListView.builder(
          itemCount: 100,
          itemExtent: 50, // 列表高度固定，性能消耗小
          controller: _controller,
          itemBuilder: (context, index) {
            return new FlatButton(
              child: ListTile(
                title: Text('$index'),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'new_page');
              },
            );
          },
        ),
      ),
      floatingActionButton: showToTopBtn == false
          ? null
          : new FloatingActionButton(
              child: Icon(Icons.arrow_upward),
              onPressed: () {
                //返回顶部时执行动画
                _controller.animateTo(.0,
                    duration: Duration(milliseconds: 200), curve: Curves.ease);
              },
            ),
    );
  }
}
